﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Diagnostics;
using System.Threading;
using System.ServiceModel;
using TestConsole.SmsService;
using System.ComponentModel;
using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace TestConsole
{
	class Program
	{
		static ContactServiceClient _contactClient;
		static SmsServiceClient _smsClient;

		private static String Username { get { return ConfigurationSettings.AppSettings["username"]; } }
		private static String Password { get { return ConfigurationSettings.AppSettings["password"]; } }
		static Boolean smsLoggedOn = false;
		static Boolean textSent = false;
		static Boolean contactLoggedOn = false;
		static Boolean contactsRetrieved = false;
		static Boolean groupsRetireved = false;
		static IEnumerable<Contact> contacts;
		static IEnumerable<Group> groups;
		static String message =
			"Ernie's Baptism is Saturday @ 1pm NOT 11am Everyone come support our to be newest member! Also help us prep by coming to building clean up @ 830.";

		static void Main(string[] args)
		{
			Logger.Write("First Log");
			_contactClient = new ContactServiceClient();
			_smsClient = new SmsServiceClient();

			TestRetrieveContactsAndGroupsUsingAsync();
			IEnumerable<Contact> filteredContacts = FilterContacts();
			IEnumerable<Phone> recipients = filteredContacts.Select(contact => contact.Phones.FirstOrDefault(phone => phone.Kind == InformationKind.Mobile)).Where(phone => phone != null);
			//TestSendTextUsingAsync(recipients);

			if (_contactClient.State == CommunicationState.Opened)
			{
				_contactClient.LogOff();
			}
			if (_smsClient.State == CommunicationState.Opened)
			{
				_smsClient.LogOff();
			}
		}

		private static IEnumerable<Contact> FilterContacts()
		{
			IEnumerable<Contact> filteredContacts = contacts.Where(
				c => c.Groups.Select(g => g.Name).Contains("CB2")
				&& c.Groups.Select(g => g.Name).Contains("Textable"));
			return filteredContacts;
		}

		private static void TestSendTextUsingAsync(IEnumerable<Phone> recipients)
		{
			_smsClient.LogOnCompleted += _smsClient_LogOnCompleted;
			_smsClient.LogOnAsync(Username, Password);
			while (!smsLoggedOn) { }
			_smsClient.SendSmsCompleted += _smsClient_SendSmsCompleted;
			Sms sms = new Sms
			{
				Recipients = recipients.ToList(),
				Messages = new List<Message> { new Message { Text = message } }
			};
			_smsClient.SendSmsAsync(sms);
			while (!textSent) { }
		}
		static void _smsClient_LogOnCompleted(object sender, LogOnCompletedEventArgs1 e)
		{
			smsLoggedOn = true;
		}
		static void _smsClient_SendSmsCompleted(object sender, SendSmsCompletedEventArgs e)
		{
			var a = e.Result;
			textSent = true;
		}

		private static void TestRetrieveContactsAndGroupsUsingAsync()
		{
			_contactClient.LogOnCompleted += _contactClient_LogOnCompleted;
			_contactClient.LogOnAsync(Username, Password);
			while (!contactLoggedOn) { }
			_contactClient.RetrieveAllContactsCompleted += _contactClient_RetrieveAllContactsCompleted;
			_contactClient.RetrieveAllContactsAsync();
			while (!contactsRetrieved) { }
			_contactClient.RetrieveAllGroupsCompleted += _contactClient_RetrieveAllGroupsCompleted;
			_contactClient.RetrieveAllGroupsAsync();
			while (!groupsRetireved) { }
		}

		static void _contactClient_RetrieveAllGroupsCompleted(object sender, RetrieveAllGroupsCompletedEventArgs e)
		{
			groups = e.Result;
			Console.WriteLine(groups.Count());
			//Console.Read();
			groupsRetireved = true;
		}
		static void _contactClient_RetrieveAllContactsCompleted(object sender, RetrieveAllContactsCompletedEventArgs e)
		{
			contacts = e.Result;
			Console.WriteLine(contacts.Count());
			//Console.Read();
			contactsRetrieved = true;
		}
		static void _contactClient_LogOnCompleted(object sender, LogOnCompletedEventArgs e)
		{
			contactLoggedOn = e.Result;
		}

		private static void TextSendTest()
		{
			IEnumerable<Contact> textableContacts = GetContactGroup(_contactClient, "Textable");

			for (int i = 0; i < 20; i++)
			{
				IEnumerable<Message> messages = new List<Message>(new Message[] { new Message { Text = i.ToString() } });
				Sms sms = ConstructSMS(textableContacts, messages);

				try
				{
					Boolean result = _smsClient.SendSms(sms);
				}
				catch (Exception)
				{
					Debugger.Break();
				}
			}

		}
		private static Sms ConstructSMS(IEnumerable<Contact> textableContacts, IEnumerable<Message> messages)
		{
			Sms sms = new Sms();
			sms.Messages = messages.ToList();
			sms.Recipients = new List<Phone>();
			foreach (Contact contact in textableContacts)
			{
				foreach (Phone phone in contact.Phones)
				{
					if (phone.Kind == InformationKind.Mobile)
					{
						((List<Phone>)sms.Recipients).Add(phone);
						break;
					}
				}
			}
			return sms;
		}
		private static IEnumerable<Contact> GetContactGroup(ContactServiceClient contactsClient, String groupName)
		{
			IEnumerable<Contact> textableContacts = contactsClient.RetrieveAllContacts().Where(
				new Func<Contact, bool>(contact => contact.Groups.Where(
					new Func<Group, bool>(group => group.Name == groupName)).Count() > 0));

			return textableContacts;
		}
	}
}
